﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Application.Service.Sys.Dto;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core.Entity.Equipment;
using LimaLims.Core.Entity.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LimaLims.Application.Service.Sys
{
    /// <summary>
    /// 系统通知API
    /// </summary>
    [ApiDescriptionSettings(Name = "SysNotice", Order = 172)]
    [Route("api")]
    public class SysNoticeService : ISysNoticeService, IDynamicApiController, ITransient
    {
        private readonly IRepository<SysNotice> _sysNoticeRep;  // 系统通知表仓储

        public SysNoticeService(IRepository<SysNotice> sysNoticeRep)
        {
            _sysNoticeRep = sysNoticeRep;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("sysNotice/add")]
        public async Task Add(AddSysNoticeInput input)
        {
            var isExist = await _sysNoticeRep.DetachedEntities.AnyAsync(u => u.Title == input.Title);
            if (isExist)
                throw Oops.Oh("已存在相同标题的公告通知");

            var sysNotice = input.Adapt<SysNotice>();

            sysNotice.Status = Core.Enum.NoticeStatus.Draft;
            await sysNotice.InsertAsync();
        }

        /// <summary>
        /// 首页获取前十条发布的通知
        /// </summary>
        /// <returns></returns>
        [HttpGet("sysNotice/homeTop")]
        public async Task<List<SysNotice>> Home()
        {
            var sysNotices = await _sysNoticeRep.DetachedEntities.Where(u => u.ValidStatus && u.Status == Core.Enum.NoticeStatus.Release)
                .OrderByDescending(s => s.CreatedTime)
                .Take(10)
                .ToListAsync();

            return sysNotices;
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <returns></returns>
        [HttpPost("sysNotice/release")]
        public async Task Release(long id)
        {
            var sysNotice = await _sysNoticeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (sysNotice == null)
                throw Oops.Oh("不存在此数据");
            sysNotice.Status = Core.Enum.NoticeStatus.Release;
            await _sysNoticeRep.UpdateIncludeAsync(sysNotice, new[] { nameof(sysNotice.Status) });
        }

        /// <summary>
        /// 撤回
        /// </summary>
        /// <returns></returns>
        [HttpPost("sysNotice/revoke")]
        public async Task Revoke(long id)
        {
            var sysNotice = await _sysNoticeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (sysNotice == null)
                throw Oops.Oh("不存在此数据");

            sysNotice.Status = Core.Enum.NoticeStatus.Revoke;
            await _sysNoticeRep.UpdateIncludeAsync(sysNotice, new[] { nameof(sysNotice.Status) });
        }

        [HttpPost("sysNotice/delete")]
        public async Task Delete(long id)
        {
            var sysNotice = await _sysNoticeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (sysNotice == null)
                throw Oops.Oh("不存在此数据");

            await sysNotice.DeleteAsync();
        }

        [HttpGet("sysNotice/detail")]
        public async Task<SysNotice> Detail(long id)
        {
            var sysNotice = await _sysNoticeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (sysNotice == null)
                throw Oops.Oh("不存在此数据！");
            return sysNotice;
        }

        [HttpPost("sysNotice/edit")]
        public async Task Edit(EditSysNoticeInput input)
        {
            var sysNotice = await _sysNoticeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (sysNotice == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _sysNoticeRep.DetachedEntities.AnyAsync(u => u.Title == input.Title && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同标题的公告通知");

            var sysNoticeModel = input.Adapt<SysNotice>();

            await sysNoticeModel.UpdateAsync();
        }


        [HttpGet("sysNotice/page")]
        public async Task<PageResult<SysNoticeOutput>> QueryPage([FromQuery] SysNoticePageInput input)
        {
            var searchValue = !string.IsNullOrEmpty(input.SearchValue?.Trim());

            var sysNotices = await _sysNoticeRep.DetachedEntities
                                         .Where((searchValue, u => EF.Functions.Like(u.Title, $"%{input.SearchValue.Trim()}%")))
                                         .Where(input.Status.HasValue, u => u.Status == input.Status)
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new SysNoticeOutput
                                         {
                                             Id = u.Id,
                                             Title = u.Title,
                                             Content = u.Content,
                                             Status = u.Status,
                                             ValidStatus = u.ValidStatus,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return sysNotices;
        }
    }
}
